package com.zjsru.plan2024.oneday;

import com.zjsru.common.Node;

import java.util.ArrayList;
import java.util.List;

/**
 * N 叉树的后序遍历
 *
 * @Author: cookLee
 * @Date: 2024-02-19
 */
public class Postorder {

    /**
     * 输入：root = [1,null,3,2,4,null,5,6]
     * 输出：[5,6,3,2,4,1]
     * \
     * 输入：root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14]
     * 输出：[2,6,14,11,7,3,12,8,4,13,9,10,5,1]
     * \
     * @param args args
     */
    public static void main(String[] args) {
        Postorder postorder = new Postorder();
        // 构建节点
        Node node5 = new Node(5);
        Node node6 = new Node(6);
        List<Node> children3 = new ArrayList<>();
        children3.add(node5);
        children3.add(node6);
        Node node3 = new Node(3, children3);

        Node node2 = new Node(2);
        Node node4 = new Node(4);

        List<Node> children1 = new ArrayList<>();
        children1.add(node3);
        children1.add(node2);
        children1.add(node4);
        Node root = new Node(1, children1);

        System.out.println(postorder.postorder(root));
    }

    /**
     * 后置处理
     *
     * @param root 根
     * @return {@link List}<{@link Integer}>
     */
    public List<Integer> postorder(Node root) {
        List<Integer> ans = new ArrayList<>();
        this.dfs(root,ans);
        return ans;
    }

    /**
     * 深度搜索助手类
     *
     * @param root 根
     */
    private void dfs(Node root, List<Integer> ans) {
        if (root == null) {
            return;
        }
        if (root.children != null) {
            for (Node node : root.children) {
                this.dfs(node, ans);
            }
        }
        ans.add(root.val);
    }

}
